module MessagesHelper
  def get_author_name
    return get_first_name
  end
    
  def get_author_url(user=get_user)
    return user == nil ? '' : user.openid_url
  end
    
  def get_user(user_id=@session[:user_id])
    return user_id == nil ? nil : User.find(user_id)
  end
  
  def get_first_name(name_array=get_name_array)
    return (name_array != nil and not name_array.empty?) ? name_array[0] : ''
  end
  
  def get_full_name(name_array=get_name_array)
    return (name_array != nil and not name_array.empty?) ? name_array.join(' ') : ''
  end
  
  def get_last_name(name_array=get_name_array)
    last_name = ''
    if name_array != nil and not name_array.empty?
      last_name = name_array[2] || name_array[1]
    end
    return last_name
  end
  
  def get_display_name(user_id=@session[:user_id]) 
    user = get_user(user_id)
    name_array = get_name_array(get_author_url(user))
    return get_first_name( name_array)
  end
  
  def get_name_array(openid_url=get_author_url)
    scan_array = nil
    if openid_url != nil and not openid_url.empty?
      # the openid_url should be fairly predictable. Right now we should support:
      # 1) http://first.last.domain.com
      # 2) http://login.domain.edu
      
      scan_array = openid_url.scan(/\w+/)
      # so this isn't the best way of doing this, but until OpenID allows for simple
      # queries to get user data (or we figure out how to do that) we can simply get
      # the user's name from their OpenID Identifier.
      if scan_array != nil and not scan_array.empty?
        # pop the com | net | org | edu ... etc. from the back
        scan_array.pop
        # pop the domain; 'myopenid' etc.
        scan_array.pop
        # remove the first entry, this should be the protocol; 'http'
        scan_array.shift
      end
    end
    return scan_array
  end
  
  def get_child_messages(params)
    id = params[:id]
    child_messages = nil
    
    current_message = Message.find(id)
    
    if current_message != nil
      child_messages = current_message.all_children
    end
    return child_messages
  end
  
end
